﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AutoMapper;
using AutoPartsSearch.Domain.Abstract.Repositories;
using AutoPartsSearch.Domain.Entities;
using AutoPartsSearch.Web.Areas.Administration.Models.BlackList;
using AutoPartsSearch.Web.ViewModels;

namespace AutoPartsSearch.Web.Controllers
{
    public class BlackListController : Controller
    {
        private IBlackListRepository _blackListRepository;
        private ISellerRepository _sellerRepository;

        public BlackListController(IBlackListRepository repository, ISellerRepository sellerRepository)
        {
            this._blackListRepository = repository;
            this._sellerRepository = sellerRepository;
        }

        public ActionResult CheckSeller()
        {
            return View();
        }

        [HttpPost]
        public ActionResult CheckSeller(string code)
        {
            Guid guid;
            if (!Guid.TryParse(code, out guid))
            {
                ModelState.AddModelError("SellerCode", "Неправильный код.");
                return View((object) code);
            }
            var seller = _sellerRepository.GetByCode(guid);
            ViewBag.Seller = seller;
            var blackList = _blackListRepository.GetBySellerCode(guid);
            return View("CheckSellerResult", blackList);
        }

        public ActionResult Add()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Add(BlackListAdd blackListAdd)
        {
            if (!ModelState.IsValid)
            {
                return View(blackListAdd);
            }

            var seller = _sellerRepository.GetByCode(blackListAdd.SellerCode);
            if (seller == null)
            {
                ModelState.AddModelError("Seller", "Seller cannot be found");
                return View(blackListAdd);
            }

            var bl = Mapper.Map<BlackList>(blackListAdd);
            bl.Seller = new Seller {Id = seller.Id};
            _blackListRepository.Add(bl);
            return RedirectToAction("Index", "SearchQuery");

        }

        public ActionResult List(int page = 1, int pageSize = 3)
        {
            var result = _blackListRepository.GetApproved(page, pageSize);
            var viewModel = new ViewModel()
            {
                BlackLists = result,
                PagingInfo = new PagingInfo()
                {
                    CurrentPage = page,
                    ItemsPerPage = pageSize,
                    TotalItems = _blackListRepository.GetTotalCount()
                }
            };
            return View(viewModel);
        }

    }
}
